package online.westonline.com.westonline.adapter.constacts;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.easy.west.westclient.Constants;
import com.easy.west.westclient.api.constacts.bean.HumanList;
import com.easy.west.westclient.api.constacts.bean.PersonBean;
import com.easy.west.westclient.api.department.bean.AllDepartMentBean;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.model.UserInfo;
import de.hdodenhof.circleimageview.CircleImageView;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.entry.EmmmBean;
import online.westonline.com.westonline.ui.OneContactActivity;
import online.westonline.com.westonline.utils.CacheUtils;
import online.westonline.com.westonline.utils.GsonUtils;
import online.westonline.com.westonline.utils.ToastUtils;
import online.westonline.com.westonline.wedgit.DownImgView;

/**
 * 联系人适配器
 * Created by xiatao on 2018/8/20.
 */

public class ConstactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {



    //联系人类型
    private int CONSTACTS_TYPE = 0x31234;
    //部门类型
    private int DEPARTMENT_TYPE = 0x16161;
    //空
    private int EMPTY_TYPE = 0x1241;
    private EmmmBean emmmBean;
    private List<Object> listdata = new ArrayList<>();

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = null;
        if (viewType == CONSTACTS_TYPE) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.constacts_item, parent, false);
            return new ConstactsViewHolder(view);
        } else if (viewType == DEPARTMENT_TYPE) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.department_item, parent, false);
            return new ChildDepartMentViewHolder(view);
        } else if (viewType == EMPTY_TYPE) {
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.empty_view, parent, false);
            return new EmptyTypeViewHolder(view);
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ConstactsViewHolder) {
            final PersonBean bean = (PersonBean) listdata.get(position);
            final ConstactsViewHolder viewHolder = (ConstactsViewHolder) holder;
            viewHolder.tvConstatsName.setText(bean.getName());
            //获取用户实体
            JMessageClient.getUserInfo(bean.getAccess_token(), new GetUserInfoCallback() {
                @Override
                public void gotResult(int i, String s, UserInfo userInfo) {
                    if (i == 0) {
                        //获取头像
                        userInfo.getBigAvatarBitmap(new GetAvatarBitmapCallback() {
                            @Override
                            public void gotResult(int i, String s, Bitmap bitmap) {
                                if (i == 0) {
                                    viewHolder.imgConstactsAvator.setImageBitmap(bitmap);
                                }
                            }
                        });
                    }
                }
            });
            viewHolder.tvConstatsPhone.setText(bean.getPhonenum()+"(手机号)");
            viewHolder.tvConstactsZuoji.setText(bean.getTel()+"(座机号)");
            viewHolder.tvConstatsPosition.setText(bean.getPosition());
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(viewHolder.itemView.getContext(), OneContactActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("data", bean);
                    intent.putExtras(bundle);
                    viewHolder.itemView.getContext().startActivity(intent);
                }
            });
        }
        if (holder instanceof ChildDepartMentViewHolder) {

            final AllDepartMentBean.DataBean.DepartmentDTOSBean bean = (AllDepartMentBean.DataBean.DepartmentDTOSBean) listdata.get(position);
            final ChildDepartMentViewHolder viewHolder = (ChildDepartMentViewHolder) holder;
            //这里每次点开还是要查一查,但是先把储存的内容先展示出来,而且是点击过后及展示,随后查
            final List<PersonBean> personBeansList = CacheUtils.getInstance().getDepartMentConstacts(bean.getDid() + bean.getName());
            if (personBeansList != null) {
                EmmmBean emmmBean = new EmmmBean();
                emmmBean.setPersonBeanList(personBeansList);
                viewHolder.setDatas(emmmBean, viewHolder.recyclerViewChildPeople);
            }
            viewHolder.tvDepartmentTitle.setText(bean.getName());
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (viewHolder.imgExpand.isShow()) {
                        viewHolder.imgExpand.show(false);
                        viewHolder.recyclerViewChildPeople.setVisibility(View.GONE);
                    } else {
                        viewHolder.proConstactsState.setVisibility(View.VISIBLE);
                        viewHolder.recyclerViewChildPeople.setVisibility(View.VISIBLE);
                        getChildConstacts(bean, viewHolder, personBeansList);
                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return listdata == null ? 0 : listdata.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (listdata.size() > 0) {
            if (listdata.get(position) instanceof AllDepartMentBean.DataBean.DepartmentDTOSBean) {
                return DEPARTMENT_TYPE;
            } else {
                return CONSTACTS_TYPE;
            }
        } else {
            return EMPTY_TYPE;
        }
    }

    public void setDatas(EmmmBean datas) {
        this.emmmBean = datas;
        if (emmmBean.getDepartMentBeanList() != null) {
            listdata.addAll(emmmBean.getDepartMentBeanList());
        }
        if (emmmBean.getPersonBeanList() != null) {
            listdata.addAll(emmmBean.getPersonBeanList());
        }

    }


    /***
     * 联系人的viewholder
     */
    class ConstactsViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.tv_search_state_desc)
        TextView tvSearchStateDesc;
        @BindView(R.id.img_constacts_avator)
        CircleImageView imgConstactsAvator;
        @BindView(R.id.tv_constats_name)
        TextView tvConstatsName;
        @BindView(R.id.tv_constats_phone)
        TextView tvConstatsPhone;
        @BindView(R.id.tv_constacts_zuoji)
        TextView tvConstactsZuoji;
        @BindView(R.id.tv_constats_position)
        TextView tvConstatsPosition;
        @BindView(R.id.tv_from_department)
        TextView tvFromDepartment;

        public ConstactsViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }


    /***
     * 部门适配器
     */
    class ChildDepartMentViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.img_expand)
        DownImgView imgExpand;
        @BindView(R.id.tv_department_title)
        TextView tvDepartmentTitle;
        @BindView(R.id.tv_state)
        TextView tvState;
        @BindView(R.id.recyclerView_child_people)
        RecyclerView recyclerViewChildPeople;
        @BindView(R.id.pro_constacts_state)
        ProgressBar proConstactsState;

        public ChildDepartMentViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        /**
         * 设置数据源
         *
         * @param emmmBean
         * @param recyclerViewChildPeople
         */
        public void setDatas(EmmmBean emmmBean, RecyclerView recyclerViewChildPeople) {
            ConstactsAdapter constactsAdapter = new ConstactsAdapter();
            recyclerViewChildPeople.setLayoutManager(new LinearLayoutManager(this.itemView.getContext()));
            recyclerViewChildPeople.setAdapter(constactsAdapter);
            constactsAdapter.setDatas(emmmBean);
            constactsAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 空
     */
    class EmptyTypeViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_empty_desc)
        TextView tvEmptyDesc;

        public EmptyTypeViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    /**
     * 请求联系人列表
     *
     * @param departMent
     * @param viewHolder
     * @param personBeansList
     */
    private void getChildConstacts(final AllDepartMentBean.DataBean.DepartmentDTOSBean departMent, final ChildDepartMentViewHolder viewHolder, List<PersonBean> personBeansList) {
        RequestParams params = new RequestParams(Constants.CONSTACTS_URL + departMent.getDid());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                HumanList humanList = GsonUtils.parseJSON(result, HumanList.class);
                EmmmBean emmmBean = new EmmmBean();
                emmmBean.setPersonBeanList(humanList.getData());
                //根据部门id储存
                //再更新
                CacheUtils.getInstance().saveDepartMentConstacts(departMent.getDid(), humanList.getData());
                //调用展开方法
                viewHolder.imgExpand.show(true);
                viewHolder.proConstactsState.setVisibility(View.GONE);
                //设置数据
                viewHolder.setDatas(emmmBean, viewHolder.recyclerViewChildPeople);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.showToast("网络出了点问题:" + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
